/**
* @author Ashish Gupta
* CVSSP, University of Surrey
* Copyright (c) 2010 Ashish Gupta
* All rights reserved.
*/
/**
 * 
 */
package uk.surrey.ash.ga;

import java.util.ArrayList;
import java.util.Random;

/**
 * @author Ashish
 *
 */
public class Chromosome {
	private Gene[] chromosome;
	private Codebook codebook;
	
	public Gene[] getChromosome() {
		return chromosome;
	}

	public void setChromosome(Gene[] chromosome) {
		this.chromosome = chromosome;
	}
	/**
	 * @param numberOfGenes 
	 * @param cellspace 
	 * @param chromosome
	 */
	public Chromosome(int numberOfGenes, CellSpace cellspace) {
		codebook = new Codebook(numberOfGenes);
		chromosome = new Gene[numberOfGenes];
		for(int i=0;i<numberOfGenes;i++){
			chromosome[i] = new Gene();
		}
		Random rg = new Random();
		for(int i=0;i<cellspace.getCells().size();i++){
			int geneIdx = rg.nextInt(numberOfGenes);
			Cell cell = cellspace.getCells().get(i);
			codebook.addCell(geneIdx,cell.getImageClass());
			chromosome[geneIdx].getGene().add(cell);
			codebook.computeCodebookFitness();
		}
	}
	

	/**
	 * @param population
	 * @param i
	 */
	public Chromosome(ArrayList<Chromosome> population, int fatherChromosomeIdx) {
		Random rg = new Random();
		int motherChromosomeIdx = rg.nextInt(population.size()/2);	// we are considering the top 50%
		int numberOfGenes = population.get(fatherChromosomeIdx).chromosome.length;
		this.chromosome = new Gene[numberOfGenes];
		for(int i=0;i<numberOfGenes/2;i++){
			Gene gene = new Gene(population.get(fatherChromosomeIdx).chromosome[i].getGene());
			this.chromosome[i] = gene;
		}
		for(int i=numberOfGenes/2;i<numberOfGenes;i++){
			Gene gene = new Gene(population.get(motherChromosomeIdx).chromosome[i].getGene());
			this.chromosome[i] = gene;
		}
//		compute the codebook of the chromosome
		codebook = new Codebook(numberOfGenes);
		codebook.scoreHistograms(chromosome);
		codebook.computeCodebookFitness();
	}


	/**
	 * 
	 */
	public Chromosome() {
	}

	/**
	 * @return the codebook
	 */
	public Codebook getCodebook() {
		return codebook;
	}

	/**
	 * 
	 */
	public void printChromosomeCodebook() {
		System.out.print("Positive Histogram:  ");
		for(int i=0;i<codebook.getHistogramPositive().length;i++){
			System.out.print(codebook.getHistogramPositive()[i] + " ");
		}
		System.out.println();
		System.out.print("Negative Histogram:  ");
		for(int i=0;i<codebook.getHistogramNegative().length;i++){
			System.out.print(codebook.getHistogramNegative()[i] + " ");
		}
		System.out.println();
	}

	/**
	 * 
	 */
	public void printChromosomeFitness() {
		System.out.println("CodebookFitness: " + codebook.getCodebookFitness());
	}
}
